python


What is a Function in Python? A function is a block of code that performs a specific task and can be reused whenever needed.

 

File Handling in Python – Read, Write, and Manage Files

File handling is an essential part of any programming language. In Python, it allows you to store data permanently and retrieve it later. Whether you’re saving user input, reading configuration files, or working with logs, Python makes file handling simple and powerful.



  Why File Handling?

Programs often need to:

* Read data from a file (like a text document)
* Write data to a file (like saving user info)
* Update existing files
* Delete files



  Opening a File in Python

Use the `open()` function:


file = open("example.txt", "r")


Syntax:


open(filename, mode)


 Common Modes

* `"r"` → Read (default)
* `"w"` → Write (overwrites file)
* `"a"` → Append (adds to file)
* `"x"` → Create a new file
* `"b"` → Binary mode (e.g., `"rb"`, `"wb"`)



  Reading a File


file = open("example.txt", "r")
content = file.read()
print(content)
file.close()


Other read methods:

* `read(n)` → Reads first `n` characters
* `readline()` → Reads one line
* `readlines()` → Reads all lines as a list

Example:


file = open("example.txt", "r")
print(file.readline())   Reads one line
file.close()




  Writing to a File


file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()


Append Mode:


file = open("example.txt", "a")
file.write("\nAdding new content.")
file.close()




  Using `with` Statement (Best Practice)

Using `with` automatically closes the file after use:


with open("example.txt", "r") as file:
    content = file.read()
    print(content)




  Check if File Exists

Use the `os` module:


import os

if os.path.exists("example.txt"):
    print("File exists")
else:
    print("File not found")




  Deleting a File


import os
os.remove("example.txt")




Example: Complete File Handling


 Writing to a file
with open("data.txt", "w") as f:
    f.write("Python File Handling Example")

 Reading the file
with open("data.txt", "r") as f:
    print(f.read())




  Summary

* Use `open(filename, mode)` for file operations.
* Modes: `"r"` (read), `"w"` (write), `"a"` (append), `"x"` (create).
* Always close files or use with statement.
* Use `os` module for file management.